package com.jswdwsx.esign.util

import com.jswdwsx.esign.commom.ResEnum
import com.jswdwsx.esign.exception.EsignBusinessException
import org.springframework.util.Base64Utils
import org.springframework.util.DigestUtils
import org.springframework.web.multipart.MultipartFile
import java.security.MessageDigest
import java.util.*


fun base64Image(file: MultipartFile): String {
    val fileContent = file.bytes
    return Base64.getEncoder().encodeToString(fileContent)
        ?: throw EsignBusinessException(ResEnum.Base64ImageFail)
}

fun md5File(file: MultipartFile): String {
    val md5Digest = DigestUtils.md5Digest(file.inputStream)
    return Base64Utils.encodeToString(md5Digest)
}

fun md5FileClassical(file: MultipartFile): String? {
    val encoder = Base64.getEncoder()
    val fileMD5Bytes128 = getFileMD5Bytes128(file)
    return encoder.encodeToString(fileMD5Bytes128)
}

fun getFileMD5Bytes128(file: MultipartFile): ByteArray? {
    var md5Bytes: ByteArray? = null

    file.inputStream.use {
        val md5 = MessageDigest.getInstance("MD5")
        md5.update(it.readBytes())
        md5Bytes = md5.digest()
    }
    return md5Bytes
}

